package com.google.code.yargon.db;

import java.sql.*;
import java.util.HashMap;

import org.apache.log4j.Logger;

import com.google.code.yargon.util.LogUtil;


/**
 * DB interface
 * 
 * @author Mika Myllynen
 *
 */
public class Dao {
	
	private HashMap<String, Connection> connections = null;
	private Logger log = LogUtil.getInstance();		

	/**
	 * Dao instance - singleton class
	 */
	private static Dao instance = null;
	public static Dao getInstance() {
		if(null == instance) {
			instance = new Dao();
		}
		return instance;
	}
	
	private Dao() {
		connections = new HashMap<String, Connection>(); 
	}
	
	/**
	 * Get (and create if necessary) connection to database file
	 * 
	 * @param fileName
	 * @return
	 */
	public Connection getConnection(String fileName) {
		Connection conn = connections.get(fileName);
		if(null == conn) {
			
			try {
				Class.forName("org.sqlite.JDBC");
				conn = DriverManager.getConnection("jdbc:sqlite:"+fileName);
				conn.setAutoCommit(false);
			} catch(Exception e) {
				log.error("Could not initialize SQLite connection to database file: "+e.getMessage());
			}	
			connections.put(fileName,  conn);
			
		}
		
		return conn;
	}
}
